import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";

const FormSchema = z.object({
  username: z.string().min(2, {
    message: "Username must be at least 2 characters."
  }),
  password: z.string().min(2, {
    message: "Password must be at least 2 characters."
  })
});

function App() {
  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      username: "",
      password: ""
    }
  });
  function onSubmit(data: z.infer<typeof FormSchema>) {
    console.log("提交的数据:", data);

    fetch("/api/sso/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
      .then(async res => {
        console.log("响应状态:", res.status);

        if (!res.ok) {
          // 如果响应不成功，抛出错误
          const errorText = await res.text();
          throw new Error(`HTTP ${res.status}: ${errorText}`);
        }

        return res.json();
      })
      .then(data => {
        console.log("成功响应:", data);

        if (data.success) {
          toast.success("登录成功!");

          // 获取会话信息
          const { sessionId, user } = data.data;
          console.log("会话ID:", sessionId);
          console.log("用户信息:", user);

          // 延迟一下让用户看到成功提示，然后重定向到 web-editor
          setTimeout(() => {
            // 重定向到 web-editor，并传递必要的参数
            window.location.href = `http://localhost:5173/?sessionId=${sessionId}&username=${user.username}`;
          }, 1500);
        } else {
          toast.error(data.message || "登录失败");
        }
      })
      .catch(error => {
        console.error("请求失败:", error);
        toast.error(`登录失败: ${error.message}`);
      });
  }
  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6">
        <FormField
          control={form.control}
          name="username"
          render={({ field }) => (
            <>
              <FormItem>
                <FormLabel>Username</FormLabel>
                <FormControl>
                  <Input className="border-[#000]" placeholder="账号" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            </>
          )}
        />
        <FormField
          control={form.control}
          name="password"
          render={({ field }) => (
            <>
              <FormItem>
                <FormLabel>password</FormLabel>
                <FormControl>
                  <Input placeholder="密码" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            </>
          )}
        />
        <Button type="submit">Submit</Button>
      </form>
    </Form>
  );
}

export default App;
